var puppeteer = require("puppeteer");
var path = require('path')

var get_browser = async() => puppeteer.launch({
    headless: false,
    timeout: 600000,
    devtools: false,
    // executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'
})
var get_page = async(browser) => browser.newPage();

async function waitForNavigation(page) {
    try {
        console.log('开始：', Date())
        await page.waitForNavigation();
        console.log('完成：', Date())
    } catch (error) {
        console.log('错误：', Date())
    }
}
async function waitSkip(page) {
    const url = await page.url()
    let _url;
    let seconds = 0;
    try {
        console.log('跳转开始：', Date())
        while (true) {
            await page.waitFor(1 * 1000);
            _url = await page.url()
            if (_url === url || seconds > 60) {
                break;
            }
            seconds = seconds + 1
            continue
        }
        console.log('跳转结束：', Date())
        await page.waitForNavigation();
        console.log('跳转完成：', Date())
    } catch (error) {
        console.log('加载错误：', Date())
        await page.waitFor(10 * 1000);
        console.log('跳转错误：', Date())
    }
}

async function goto_login(page) {
    await page.goto("https://sell.souq.com/sell", {
        timeout: 60 * 1000
    });
    await waitSkip(page)
}
async function login(_page) {
    // const page = await _page;
    await page.type("#email", "hjg68666@163.com");
    await page.type('input[name="password"]', "qq000123");
    await page.click(".login-button button");
    await waitSkip(page);
}

async function goto_search(_page) {
    const page = await _page;
    await page.goto("https://sell.souq.com/inventory/search-results/Girls/t=487");
    await waitSkip(page);
}

async function goto_form(page) {
    (await page).click("#main div.hide-for-large-up.category-toggle > div.button.ng-binding.ng-scope");
    await waitSkip(page);
}

async function entry_form1(_page) {
    const page = await _page
    await page.select('#itemListitng select[name="Targeted Group0"]', 'Girls');
    await page.select('#itemListitng select[name="Swimwear Type1"]', 'Bikini Set');
    await page.select('#itemListitng select[name="Brand2"]', 'Chelly');
    await page.select('#itemListitng select[name="Color0"]', 'object:2761');
    await page.select('#itemListitng select[name="Size1"]', 'object:2943');
}

async function upload(_page) {
    const page = await _page
    const filePath = process.cwd() + '/images/img01.jpg'
    const input = await page.$('input[type="file"]');
    await input.uploadFile(filePath);
    await page.evaluate(e => e.files[0].name, input)
    await page.evaluate(e => {
        const reader = new FileReader();
        const promise = new Promise(fulfill => reader.onload = fulfill);
        reader.readAsText(e.files[0]);
        return promise.then(() => reader.result);
    }, input)
    await page.click('#itemListitng > div.actions-fixed-menu > button.tiny.radius.primary.ng-binding')
    await waitSkip(page)
};

async function entry_form2(_page) {
    const page = await _page
    await page.type('#offerListitng .count input[name="amount"]', '50');
    await page.type('#offerListitng .price input[name="offerPrice"]', '100');
    await page.type('#offerListitng .sku input[name="sku"]', '15638667111');
    await page.type('#offerListitng .note textarea[name="notetx"]', "balabala");
    await page.select('#offerListitng .delivery_time select[name="handling_time"]', 'Same Day');
    await page.click('button[type="submit"]')
    await waitSkip(page)
    await page.click('button[type="submit"]')
    await waitSkip(page)
}

var test = async _page => {
    page.then(p => p.select('#offerListitng .delivery_time select[name="handling_time"]', 'string:a'))
    page.then(p => p.click('button[type="submit"]'))
    page.then(p => p.goto("https://sell.souq.com/inventory/create-item?subcategory=487"))
};

var title = async _page => {
    const page = await _page;
    const title = await page.title();
    console.log(title);
};

async function close(browser) {
    (await browser).close();
}
var browser;
var page;
async function init() {
    browser = await get_browser();
    console.log(browser);
    page = await get_page(browser)
    console.log('打开浏览器……');
}
async function run() {
    await goto_login(page);
    console.log('正在登陆……');
    await login(page);
    console.log('登录完成！');
    await goto_search(page);
    console.log('进入搜索页面……');
    await goto_form(page);
    console.log('进入表单1页面……');
    await entry_form1(page);
    console.log('上传图像……');
    await upload(page);
    console.log('进入表单2页面……');
    await entry_form2(page);
}